import 'dart:async';
import 'package:flutter/material.dart';
import 'dart:ui' as ui;
import 'package:lx_widgets_library/const/font_weight.dart';

// 水印组件
// 该组件可以添加文本或图片水印
class WaterMarkView extends StatelessWidget {
  final Widget child; // 子组件
  final String? text; // 水印文本
  final ImageProvider? image; // 水印图片
  final double opacity; // 水印透明度
  final Color color; // 水印颜色
  final LxFontWeightEnum lxFontWeight; // 文字大小
  final double rotate; // 旋转角度
  final double spacing; // 水印间距

  const WaterMarkView({
    Key? key,
    required this.child,
    this.text,
    this.image,
    this.opacity = 0.1,
    this.color = Colors.grey,
    this.lxFontWeight = LxFontWeightEnum.headlineSmall,
    this.rotate = -20,
    this.spacing = 100,
  })  : assert(text != null || image != null, '必须提供text或image'),
        super(key: key);

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        child, // 底层子组件
        Positioned.fill(
          child: IgnorePointer(
            // 忽略触摸事件，使水印不影响下层组件的交互
            child: ClipRect(
              child: CustomPaint(
                painter: _WaterMarkPainter(
                  text: text,
                  image: image,
                  opacity: opacity,
                  color: color,
                  lxFontWeight: lxFontWeight,
                  rotate: rotate,
                  spacing: spacing,
                ),
              ),
            ),
          ),
        ),
      ],
    );
  }
}

class _WaterMarkPainter extends CustomPainter {
  final String? text; // 水印文本
  final ImageProvider? image; // 水印图片
  final double opacity; // 透明度
  final Color color; // 颜色
  final LxFontWeightEnum lxFontWeight; // 字体大小
  final double rotate; // 旋转角度（度数）
  final double spacing; // 水印间距

  _WaterMarkPainter({
    required this.text,
    required this.image,
    required this.opacity,
    required this.color,
    required this.lxFontWeight,
    required this.rotate,
    required this.spacing,
  });

  @override
  Future<void> paint(Canvas canvas, Size size) async {
    final textStyle = TextStyle(
      color: color.withOpacity(opacity),
      fontSize: lxFontWeight.size,
      fontWeight: lxFontWeight.fontWeight,
    );

    final textSpan = TextSpan(text: text, style: textStyle);
    final textPainter = TextPainter(
      text: textSpan,
      textDirection: TextDirection.ltr,
    );
    textPainter.layout();

    // 计算绘制区域
    final centerX = size.width / 2;
    final centerY = size.height / 2;
    final radius = size.width > size.height ? size.width : size.height;

    // 绘制水印
    for (double i = -radius; i < radius; i += spacing) {
      for (double j = -radius; j < radius; j += spacing) {
        canvas.save(); // 保存当前画布状态
        canvas.translate(centerX + i, centerY + j); // 移动到指定位置
        canvas.rotate(rotate * 3.1415926535 / 180); // 转换角度为弧度并旋转

        if (text != null) {
          textPainter.paint(canvas, Offset.zero);
        } else if (image != null) {
          // 图片水印实现需要更复杂的逻辑
          final ui.Image watermarkImage = await _loadImage(image!);
          final srcSize = Size(
            watermarkImage.width.toDouble(),
            watermarkImage.height.toDouble(),
          );

          for (double i = -radius; i < radius; i += spacing) {
            for (double j = -radius; j < radius; j += spacing) {
              canvas.save();
              canvas.translate(centerX + i, centerY + j);
              canvas.rotate(rotate * 3.1415926535 / 180);

              canvas.drawImage(
                watermarkImage,
                Offset(-srcSize.width / 2, -srcSize.height / 2), // 居中绘制图片
                Paint()
                  ..colorFilter = ColorFilter.mode(
                    color.withOpacity(opacity),
                    BlendMode.srcIn,
                  ),
              );

              canvas.restore(); // 恢复画布状态
            }
          }
        }

        canvas.restore(); // 恢复画布状态
      }
    }
  }

  // 加载图片资源
  Future<ui.Image> _loadImage(ImageProvider imageProvider) async {
    final completer = Completer<ui.Image>();
    final stream = imageProvider.resolve(ImageConfiguration.empty);
    final listener = ImageStreamListener((ImageInfo info, _) {
      completer.complete(info.image);
    });
    stream.addListener(listener);
    return completer.future;
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) => false; // 避免不必要的重绘
}

// 支持动态水印
class DynamicWaterMark extends StatefulWidget {
  final Widget child; // 子组件
  final String Function() textBuilder; // 水印文本生成函数

  const DynamicWaterMark({
    super.key,
    required this.child,
    required this.textBuilder,
  });

  @override
  _DynamicWaterMarkState createState() => _DynamicWaterMarkState();
}

class _DynamicWaterMarkState extends State<DynamicWaterMark> {
  @override
  Widget build(BuildContext context) {
    return WaterMarkView(
      text: widget.textBuilder(), // 动态生成水印文本
      child: widget.child,
    );
  }
}
